package web

import (
	"github.com/gin-gonic/gin"
	"github.com/wechatpay-apiv3/wechatpay-go/core/notify"
	"github.com/wechatpay-apiv3/wechatpay-go/services/payments"
	"jk-time/webook/payment/service/wechat"
	"jk-time/webook/pkg/logger"
	"net/http"
	"time"
)

type WechatHandler struct {
	handler   *notify.Handler
	l         logger.Logger
	nativeSvc wechat.NativePaymentService
}

func NewWechatHandler(handler *notify.Handler, l logger.Logger, nativeSvc wechat.NativePaymentService) *WechatHandler {
	return &WechatHandler{handler: handler, l: l, nativeSvc: nativeSvc}
}

func (h *WechatHandler) RegisterRoutes(server *gin.Engine) {
	server.Any("/pay/callback", h.HandleNative)
}

// HandleNative 处理回调
func (h *WechatHandler) HandleNative(ctx *gin.Context) {
	//用来接收解密后的数据
	transaction := new(payments.Transaction)
	_, err := h.handler.ParseNotifyRequest(ctx, ctx.Request, transaction)
	if err != nil {
		ctx.String(http.StatusBadRequest, "参数解析失败")
		h.l.Error("解析微信支付回调失败", logger.Error(err))
		// 在这里， 你可以考虑进一步加监控和告警
		// 绝大概率是黑客在尝试攻击你
		return
	}
	// 回写数据库,发送kafka
	err = h.nativeSvc.UpdateByTxn(ctx, transaction)
	if err != nil {
		ctx.String(http.StatusInternalServerError, "系统错误")
		h.l.Error("修改订单状态、回写数据库失败", logger.Error(err))

		//处理回调失败，考虑3分钟后
		time.AfterFunc(3*time.Minute, func() {
			err := h.nativeSvc.SyncWechatInfo(ctx, *transaction.OutTradeNo)
			h.l.Info("对账状态：", logger.Error(err))
		})
		return
	}
	ctx.String(http.StatusOK, "OK")
}
